﻿--Macaroon, a World of Warcraft® user interface addon.
--Copyright© 2008 Connor H. Chenoweth, aka Maul

Macaroon.EditFrames = {}

local panels = {}

local toggleOptions = {}

local editMode, macroFrame, macroEdit, ss, playerEnteredWorld = false

local find = string.find
local lower = string.lower

local GetMouseFocus = _G.GetMouseFocus

local spellIndex = Macaroon.spellIndex
local getChildrenAndRegions = Macaroon.getChildrenAndRegions
local MACAROON_STRINGS = MACAROON_STRINGS

Macaroon.CurrentButton = nil

local function insertLink(text)

	local item = GetItemInfo(text)

	if ( macroEdit:GetText() == "" ) then

		if ( item ) then

			if ( GetItemSpell(text) ) then
				macroEdit:Insert(SLASH_USE1.." "..item)
			else
				macroEdit:Insert(SLASH_EQUIP1.." "..item)
			end

		else
			macroEdit:Insert(SLASH_CAST1.." "..text)
		end
	else
		macroEdit:Insert(item or text)
	end
end

local function modifiedSpellClick(button)

	local id = SpellBook_GetSpellID(GetMouseFocus():GetID())

	if ( id > MAX_SPELLS ) then
		return
	end

	if (CursorHasSpell() and macroFrame:IsVisible() ) then
		ClearCursor()
	end

	if ( IsModifiedClick("CHATLINK") ) then

		if ( macroFrame:IsVisible() ) then

			local spellName, subSpellName = GetSpellName(id, SpellBookFrame.bookType)

			if ( spellName and not IsPassiveSpell(id, SpellBookFrame.bookType) ) then

				if ( subSpellName and (strlen(subSpellName) > 0) and IsControlKeyDown()) then
					insertLink(spellName.."("..subSpellName..")")
				else
					insertLink(spellName)
				end
			end
			return
		end
	end

	if ( IsModifiedClick("PICKUPACTION") ) then

		PickupSpell(id, SpellBookFrame.bookType)

	end
end

local function modifiedItemClick(link)

	if ( IsModifiedClick("CHATLINK") ) then

		if ( macroFrame:IsVisible() ) then

			local itemName = GetItemInfo(link)

			if (itemName) then
				insertLink(itemName)
			end

			return true
		end
	end
end

local function modifiedCompanionClick(button)

	local id = button.spellID

	if (CursorHasSpell() and macroFrame:IsVisible() ) then
		ClearCursor()
	end

	if ( IsModifiedClick("CHATLINK") ) then

		if ( macroFrame:IsVisible() ) then

			local spellName = GetSpellInfo(id)

			if (spellName) then
				insertLink(spellName)
			end

			return
		end
	end

	if ( IsModifiedClick("PICKUPACTION") ) then

		CompanionButton_OnDrag(button)

	end

	PetPaperDollFrame_UpdateCompanions()	--Set up the highlights again

end

local function openStackSplitFrame(...)

	if ( macroFrame:IsVisible() ) then
		StackSplitFrame:Hide()
	end
end

function Macaroon.ButtonEdit(off)

	if (not off) then
		Macaroon.ConfigBars(true)
		Macaroon.ButtonBind(true)
	end

	if (editMode or off) then

		editMode = false

		Macaroon.MacroEditor_SaveMacro()

		for k,v in pairs(Macaroon.EditFrames) do

			v:Hide()
			v:SetFrameStrata("LOW")

			k.editmode = false
		end

		if (not off) then

			for k,v in pairs(Macaroon.BarIndex) do
				v.updateBarTarget(v)
				v.updateBarLink(v)
				v.updateBarHidden(v)
			end

			for k,v in pairs(Macaroon.HideGrids) do
				v(true)
			end
		end

		MacaroonButtonEditor.shrink = true
		MacaroonButtonOptions.shrink = true

		for k,v in pairs(Macaroon.StatesToSave) do v() end

	else

		editMode = true

		for k,v in pairs(Macaroon.EditFrames) do

			v:Show()
			v:SetFrameStrata(k.bar:GetFrameStrata())
			v:SetFrameLevel(k.bar:GetFrameLevel()+4)

			k.editmode = true
		end

		if (not off) then

			for k,v in pairs(Macaroon.BarIndex) do
				v.updateBarHidden(v, true)
				v.updateBarTarget(v, true)
			end

			for k,v in pairs(Macaroon.ShowGrids) do
				v(true)
			end
		end
	end
end

function Macaroon.ButtonEdit_AddPanel(panel, index)
	panels[index] = panel
end

function Macaroon.EditFrame_OnLoad(self)

	self:RegisterForClicks("AnyDown","AnyUp")
	self.elapsed = 0
	self.pushed = 0
	self.message = _G[self:GetName().."Message"]
end

function Macaroon.ChangeButton(button)

	local newBtn = false

	if (playerEnteredWorld) then

		if (button and Macaroon.CurrentButton ~= button) then

			Macaroon.CurrentButton = button

			newBtn = true
			button.editframe.selected = true
			button.editframe.action = nil

			--if (self.config.hidden) then
			--	self:SetBackdropColor(1,0,0,0.6)
			--else
			--	self:SetBackdropColor(0,0,1,0.4)
			--end

		end

		if (not button) then
			Macaroon.CurrentButton = nil
		end

		for k,v in pairs(Macaroon.Buttons) do
			if (v[1] ~= button) then

				--if (v.config.hidden) then
				--	v:SetBackdropColor(1,0,0,0.4)
				--else
				--	v:SetBackdropColor(0,0,0,0.2)
				--end

				--v:SetBackdropBorderColor(0.3,0.3,0.3,0.3)

				v[1].editframe.selected = false
				v[1].editframe.action = nil
				v[1].editframe.mousewheelfunc = nil
				v[1].editframe.message:SetText("")
			end
		end
	end

	return newBtn
end

function Macaroon.EditFrame_OnClick(self, click, down, button)

	Macaroon.MacroEditor_SaveMacro()

	if (not down) then
		self.newBtn = Macaroon.ChangeButton(button)
	end

	self.elapsed = 0; self.click = click; self.down = down

	if (click == "MiddleButton") then

		if (down) then

			if (self.action) then
				self.hover = nil
				self.elapsed = 1
			end
		end

	elseif (click == "RightButton" and not self.action and not down) then

		self.message:SetText("")

		MacaroonButtonEditor:Hide()

		if (button.showselect) then

			MacaroonButtonEditSelect:SetScale(button:GetEffectiveScale())

			MacaroonButtonEditSelect:SetPoint("TOPLEFT", button.editframe, "TOPLEFT")

			MacaroonButtonEditSelect:SetPoint("BOTTOMRIGHT", button.editframe, "BOTTOMRIGHT")

			MacaroonButtonEditSelect:Show()
		end

		MacaroonButtonEditor:ClearAllPoints()

		if (ss.checkButtons[202]) then
			MacaroonButtonEditor:SetPoint("CENTER", MacaroonPanelMover, "CENTER")
		else
			MacaroonButtonEditor:SetPoint("CENTER", button.editframe, "CENTER")
		end

		MacaroonButtonEditor:SetScale(0.01)

		MacaroonButtonEditor.scale = 0.01

		MacaroonButtonEditor.grow = true

		MacaroonButtonEditor.shrink = false

		MacaroonButtonOptions.grow = false

		MacaroonButtonOptions.shrink = true

		MacaroonButtonEditor:Show()

	elseif (not self.action and not down) then

		MacaroonButtonEditor.grow = false

		MacaroonButtonEditor.shrink = true

		MacaroonButtonOptions.grow = false

		MacaroonButtonOptions.shrink = true

		if (button.showselect) then

			MacaroonButtonEditSelect:SetScale(button:GetEffectiveScale())

			MacaroonButtonEditSelect:SetPoint("TOPLEFT", button.editframe, "TOPLEFT")

			MacaroonButtonEditSelect:SetPoint("BOTTOMRIGHT", button.editframe, "BOTTOMRIGHT")

			MacaroonButtonEditSelect:Show()
		end

		if (button.leftclick and not MacaroonButtonEditor:IsVisible() and not MacaroonButtonOptions:IsVisible()) then
			button.leftclick(button)
		end

	elseif (self.action and down) then

		if (click == "RightButton") then

			self.updateValues(self, -1, self.action)

		elseif (click == "LeftButton") then

			self.updateValues(self, 1, self.action)
		end

	end

	if (click ~= "MiddleButton") then
		Macaroon.EditFrame_OnEnter(button)
	end
end

function Macaroon.EditFrame_OnMouseWheel(self, delta, button)

	self.elapsed = 0

	if (self.updateValues) then
		self.updateValues(self, delta)
	end
end

function Macaroon.EditFrame_OnEnter(button)

	button.showselect = false

	if ( GetCVar("UberTooltips") == "1" ) then
		GameTooltip_SetDefaultAnchor(GameTooltip, button)
	else
		GameTooltip:SetOwner(button, "ANCHOR_RIGHT")
	end

	if (button.config.type == "action") then

		button.showselect = true

		local action = button.config.action

		if (action and action ~= "") then
			GameTooltip:SetAction(action)
		else
			GameTooltip:SetText(MACAROON_STRINGS.EMPTY_BUTTON)
		end

		GameTooltip:AddLine(MACAROON_STRINGS.BUTTONEDIT_TOOLTIP1..button.id.."|r", 1.0, 1.0, 1.0)

	elseif (button.config.type == "macro") then

		button.showselect = true

		local spell, item, link = button.macrospell, button.macroitem

		spell = lower(spell or "")

		if (spell and spell ~= "") then

			if (spellIndex[spell]) then

				GameTooltip:SetSpell(spellIndex[spell][1], spellIndex[spell][4])

			elseif (type(button.config.macroIcon) == "table") then

				GameTooltip:SetHyperlink("spell:"..button.config.macroIcon[5])
			end

		elseif (item and item ~= "") then

			_, link = GetItemInfo(item)

			if (link) then
				GameTooltip:SetHyperlink(link)
			end
		else
			if (strlen(button.config.macro) > 0) then
				GameTooltip:SetText(button.config.macro)
			else
				GameTooltip:SetText(MACAROON_STRINGS.EMPTY_BUTTON)
			end
		end

		GameTooltip:AddLine(MACAROON_STRINGS.BUTTONEDIT_TOOLTIP1..button.id.."|r", 1.0, 1.0, 1.0)

	elseif (button.config.type == "pet") then

		button.showselect = true

		local action = button.config.action

		if (button.isToken or not button.UberTooltips) then

			if (button.tooltipName) then
				GameTooltip:SetText(button.tooltipName, 1.0, 1.0, 1.0)

			end

			if ( button.tooltipSubtext ) then
				GameTooltip:AddLine(button.tooltipSubtext, "", 0.5, 0.5, 0.5)
			end
		else

			GameTooltip:SetPetAction(action)
		end

		GameTooltip:AddLine(MACAROON_STRINGS.BUTTONEDIT_TOOLTIP1..button.id.."|r", 1.0, 1.0, 1.0)

	elseif (button.config.type == "castbar") then

		GameTooltip:SetText(" ")
		GameTooltip:AddLine(MACAROONCB_STRINGS.WIDTH.."|cffffffff"..button.config.width.."|r")
		GameTooltip:AddLine(MACAROONCB_STRINGS.HEIGHT.."|cffffffff"..button.config.height.."|r")

		if (button.config.unit) then
			GameTooltip:AddLine(MACAROONCB_STRINGS.UNIT.."|cffffffff"..button.config.unit.."\n".."|r")
		else
			GameTooltip:AddLine(MACAROONCB_STRINGS.UNIT.."|cffffffffnone\n".."|r")
		end

		if (button.editframe.action) then
			GameTooltip:AddLine(MACAROONCB_STRINGS.CASTBAREDIT_TOOLTIP1, 1.0, 1.0, 1.0)
			GameTooltip:AddLine(MACAROONCB_STRINGS.CASTBAREDIT_TOOLTIP2, 1.0, 1.0, 1.0)
		end

		GameTooltip:AddLine(MACAROONCB_STRINGS.CASTBAREDIT_TOOLTIP3..button.id.."|r", 1.0, 1.0, 1.0)

	elseif (button.config.type == "statusbar") then

		GameTooltip:SetText(" ")
		GameTooltip:AddLine(MACAROONXP_STRINGS.WIDTH.."|cffffffff"..button.config.width.."|r")
		GameTooltip:AddLine(MACAROONXP_STRINGS.HEIGHT.."|cffffffff"..button.config.height.."\n".."|r")

		if (button.editframe.action) then
			GameTooltip:AddLine(MACAROONXP_STRINGS.XPBAREDIT_TOOLTIP1, 1.0, 1.0, 1.0)
			GameTooltip:AddLine(MACAROONXP_STRINGS.XPBAREDIT_TOOLTIP2, 1.0, 1.0, 1.0)
		end

		GameTooltip:AddLine(MACAROONXP_STRINGS.XPBAREDIT_TOOLTIP3..button.id.."|r", 1.0, 1.0, 1.0)

	end

	if (button.showselect) then

		MacaroonButtonEditSelect:SetScale(button:GetEffectiveScale())

		MacaroonButtonEditSelect:SetPoint("TOPLEFT", button.editframe, "TOPLEFT")

		MacaroonButtonEditSelect:SetPoint("BOTTOMRIGHT", button.editframe, "BOTTOMRIGHT")

		MacaroonButtonEditSelect:Show()
	end

	GameTooltip:Show()

	button.editframe.hover = true
end

function Macaroon.EditFrame_OnLeave(button)

	MacaroonButtonEditSelect:Hide()

	button.UpdateTooltip = nil

	GameTooltip:Hide()

	if (button.editframe:GetButtonState() ~= "PUSHED") then
		button.editframe.hover = nil
	end
end

function Macaroon.EditFrame_OnUpdate(self, elapsed)

	if (self.elapsed) then

		self.elapsed = self.elapsed + elapsed

		if (self.hover) then
			self.elapsed = 0
		end

		if (self.action and self.elapsed >= 0.4) then
			self.action = nil
			self.message:SetText("")
		end

		if (self.action and self.updateValues and self:GetButtonState() == "PUSHED") then

			self.pushed = self.pushed + elapsed

			if (self.pushed > 0.65) then

				if (self.click == "RightButton") then

					self.updateValues(self, -1, self.action)

				elseif (click == "MiddleButton") then

					self.hover = nil
					self.elapsed = 1
				else
					self.updateValues(self, 1, self.action)
				end
			end
		end

		if (GetMouseFocus() == self) then
			self:EnableMouseWheel(true)
		else
			self:EnableMouseWheel(false)
		end
	end
end

function Macaroon.ButtonEditor_OnClick(self)

	if (self.button == "close") then
		Macaroon.MacroEditor_SaveMacro()
		MacaroonButtonEditor.shrink = true
	end

end

function Macaroon.ButtonEditor_Toggle()

	local button = Macaroon.CurrentButton

	MacaroonButtonOptions.grow = false

	MacaroonButtonOptions.shrink = true

	MacaroonButtonEditor:ClearAllPoints()

	if (ss.checkButtons[202]) then
		MacaroonButtonEditor:SetPoint("CENTER", MacaroonPanelMover, "CENTER")
	else
		MacaroonButtonEditor:SetPoint("CENTER", button, "CENTER")
	end

	MacaroonButtonEditor:SetScale(0.01)

	MacaroonButtonEditor.scale = 0.01

	MacaroonButtonEditor.grow = true

	MacaroonButtonEditor.shrink = false

	MacaroonButtonEditor:Show()
end

function Macaroon.ButtonOptions_Toggle()

	local button = Macaroon.CurrentButton

	MacaroonButtonEditor.grow = false

	MacaroonButtonEditor.shrink = true

	MacaroonButtonOptions:ClearAllPoints()

	if (ss.checkButtons[202]) then
		MacaroonButtonOptions:SetPoint("CENTER", MacaroonPanelMover, "CENTER")
	else
		MacaroonButtonOptions:SetPoint("CENTER", button, "CENTER")
	end

	MacaroonButtonOptions:SetScale(0.01)

	MacaroonButtonOptions.scale = 0.01

	MacaroonButtonOptions.grow = true

	MacaroonButtonOptions.shrink = false

	MacaroonButtonOptions:Show()
end

function Macaroon.ButtonEditorPage_OnClick(parent)

	if (MacaroonButtonOptions:IsVisible()) then

		Macaroon.ButtonEditor_Toggle()

	elseif (MacaroonButtonEditor:IsVisible()) then

		Macaroon.ButtonOptions_Toggle()
	end
end

function Macaroon.ButtonEditor_OnShow(self)

	local button = Macaroon.CurrentButton

	for k,v in pairs(panels) do
		v:Hide()
	end

	if (button) then

		local editor = panels[button.config.type]

		if (editor) then
			editor:Show()
			self:SetHeight(editor:GetHeight()+50)
		else
			self:SetHeight(150)
		end
	else
		self:SetHeight(150)
	end
end

function Macaroon.ButtonEditor_OnHide(self)

end

function Macaroon.ButtonEditor_OnUpdate(self)

	if (self.grow) then

		if (ss.checkButtons[203]) then

			if (self.scale < 1) then
				self.scale = self.scale + 0.1
				self:SetScale(self.scale)
			else
				self:SetScale(1)
				self.grow = false
			end
		else
			self:SetScale(1)
			self.grow = false
		end

	elseif (self.shrink) then

		if (ss.checkButtons[203]) then

			if (self.scale > 0.1) then
				self.scale = self.scale - 0.1
				self:SetScale(self.scale)
			else
				self:SetScale(0.01)
				self:Hide()
				self.shrink = false
			end
		else
			self:SetScale(0.01)
			self:Hide()
			self.shrink = false
		end
	end
end

function Macaroon.ButtonEditorMacroEditMacro(self)

	if (Macaroon.CurrentButton) then
		Macaroon.CurrentButton.config.macroAuto = false
		self:SetText(gsub(self:GetText(), "#autowrite\n", ""))
	end
end

function Macaroon.ButtonEditorMacroEdit_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button and button.config.macro) then
		self:SetText(button.config.macro)
	end

end

function Macaroon.ButtonEditorMacroEdit_OnTextChanged(self)

	ScrollingEdit_OnTextChanged(self, self:GetParent())

	local button = Macaroon.CurrentButton

	if (button and not MacaroonButtonEditor.shrink and not MacaroonButtonEditor.grow) then
		button.config.macro = self:GetText()
	end

end

function Macaroon.ButtonEditorMacroEdit_OnCursorChanged(self, x, y, w, h)
	ScrollingEdit_OnCursorChanged(self, x, y, w, h)
end

function Macaroon.ButtonEditorMacroEdit_OnUpdate(self, elapsed)
	ScrollingEdit_OnUpdate(self, elapsed, self:GetParent())
end

function Macaroon.MacroEditor_SaveMacro()

	local button = Macaroon.CurrentButton

	if (button) then

		local key = GetRealmName()..":"..UnitName("player")..":"..button.id

		if (key and button.config.macro and not find(button.config.macro, "#autowrite")) then

			MacaroonMacroMaster[key] = {
				button.config.macro,
				button.config.macroIcon,
				button.config.macroName,
				button.config.macroNote,
				button.config.macroUseNote,
			}

		end

		Macaroon.SetButtonType(button)
	end

end

function Macaroon.MacroEditor_ScrollFrame2Update()

	local button = Macaroon.CurrentButton

	if (button and button.config.macroIcon) then

		local frame = MacaroonButtonEditorMacroEditScrollFrame2

		local numMacroIcons = GetNumMacroIcons()+1
		local macroPopupIcon, macroPopupButton, index, texture
		local macroPopupOffset = FauxScrollFrame_GetOffset(frame)

		local macroIcon, blankSet = button.config.macroIcon

		if (type(macroIcon) == "table") then
			MacaroonButtonEditorMacroEditMacroIconIcon:SetTexture(macroIcon[6])
		else
			MacaroonButtonEditorMacroEditMacroIconIcon:SetTexture(GetMacroIconInfo(macroIcon))
		end

		for i=1,30 do

			macroPopupIcon = _G["MacaroonButtonEditorMacroEditButton"..i.."Icon"]
			macroPopupButton = _G["MacaroonButtonEditorMacroEditButton"..i]

			index = (macroPopupOffset * 6) + i

			texture = GetMacroIconInfo(index)

			if ( index < numMacroIcons ) then

				macroPopupIcon:SetTexture(texture)
				macroPopupButton:Show()

				macroPopupButton.iconindex = index

			elseif (not blankSet) then

				macroPopupIcon:SetTexture("")
				macroPopupButton:Show()

				macroPopupButton.iconindex = 0

				blankSet = true
			else

				macroPopupIcon:SetTexture("")
				macroPopupButton:Hide()

				macroPopupButton.iconindex = 1
			end
		end

		-- Scrollbar stuff

		FauxScrollFrame_Update(frame, ceil(numMacroIcons/6), 5, 2)

		if (not MacaroonButtonEditorMacroEditMacroIcon.click) then
			frame:Hide()
		end
	end
end

function Macaroon.MacroEditor_ScrollFrame3Update()

	local btn = Macaroon.CurrentButton

	if (btn) then

		local frame = MacaroonButtonEditorMacroEditScrollFrame3

		local button, buttonIndex, buttonBody, index, text, body
		local dataOffset = FauxScrollFrame_GetOffset(frame)
		local count = 1
		local data = {}

		for k,v in pairs(MacaroonMacroMaster) do
			if (MacaroonMacroMaster[k][1] and MacaroonMacroMaster[k][1] ~= "") then
				if (find(k, "^%a")) then
					data[count] = k
					count = count + 1
				end
			end
		end

		table.sort(data)

		for i=1,6 do

			count = i+40

			button = _G["MacaroonButtonEditorMacroEditButton"..count]
			button:SetChecked(nil)
			button.tooltip = nil
			button.macro = ""
			button.macroIcon = 1
			button.macroName = ""
			button.macroNote = ""
			button.macroUseNote = false

			buttonIndex = _G["MacaroonButtonEditorMacroEditButton"..count.."MacroIndex"]
			buttonBody = _G["MacaroonButtonEditorMacroEditButton"..count.."MacroBody"]

			index = dataOffset + i

			if (data[index]) then

				button.macro = MacaroonMacroMaster[data[index]][1]
				button.macroIcon = MacaroonMacroMaster[data[index]][2]
				button.macroName = MacaroonMacroMaster[data[index]][3]
				button.macroNote = MacaroonMacroMaster[data[index]][4]
				button.macroUseNote = MacaroonMacroMaster[data[index]][5]

				buttonIndex:SetText(data[index])
				buttonBody:SetText(button.macro)
				button.tooltip = button.macro

				button:Show()
			else
				button:Hide()
			end
		end

		-- Scrollbar stuff

		count = 7

		if (#data > count) then
			count = #data
		end

		FauxScrollFrame_Update(frame, count, 6, 2)

		if (not MacaroonButtonEditorMacroEditMacroMaster.click) then
			frame:Hide()
		end
	end
end

function Macaroon.MacroEditor_OnLoad(self)

	local button, lastButton, rowButton, count, fontString, script = false, false, false, 0

	for i=1,30 do

		button = CreateFrame("CheckButton", self:GetName().."Button"..i, MacaroonButtonEditorMacroEditScrollFrame2, "MacaroonMacroButtonTemplate")
		button:SetID(i)
		button:SetFrameLevel(MacaroonButtonEditorMacroEditScrollFrame2:GetFrameLevel()+2)

		if (not lastButton) then
			if (not rowButton) then
				button:SetPoint("TOPLEFT",5,5)
				rowButton = button
			else
				button:SetPoint("TOP", rowButton, "BOTTOM", 0, -10)
				rowButton = button
			end
			lastButton = button
		else
			button:SetPoint("LEFT", lastButton, "RIGHT", 7, 0)
			lastButton = button
		end

		count = count + 1

		if (count == 6) then
			lastButton = false
			count = 0
		end
	end

	lastButton = false
	count = 0

	for i=41,46 do

		button = CreateFrame("CheckButton", self:GetName().."Button"..i, MacaroonButtonEditorMacroEditScrollFrame3, "MacaroonButtonTemplate2")
		button:SetScript("OnClick",
			function(self)
				local button, buttonIndex, buttonBody
				for i=41,46 do
					button = _G["MacaroonButtonEditorMacroEditButton"..i]
					buttonIndex = _G["MacaroonButtonEditorMacroEditButton"..i.."MacroIndex"]
					buttonBody = _G["MacaroonButtonEditorMacroEditButton"..i.."MacroBody"]
					if (i == self:GetID()) then
						MacaroonButtonEditorMacroEditScrollFrame3.currButton = self
					else
						button:SetChecked(nil)
					end
				end
			end
		)

		fontString = button:CreateFontString(button:GetName().."MacroIndex", "ARTWORK", "GameFontNormalSmall");
		fontString:SetPoint("BOTTOMLEFT", button, "LEFT")
		fontString:SetPoint("TOPRIGHT", button, "TOPRIGHT")
		fontString:SetJustifyH("LEFT")

		fontString = button:CreateFontString(button:GetName().."MacroBody", "ARTWORK", "GameFontNormalSmall");
		fontString:SetPoint("TOPLEFT", button, "LEFT")
		fontString:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT")
		fontString:SetJustifyH("LEFT")
		fontString:SetTextColor(1,1,1)

		button:SetID(i)
		button:SetFrameLevel(MacaroonButtonEditorMacroEditScrollFrame3:GetFrameLevel()+2)
		button:SetNormalTexture("")

		button:SetWidth(MacaroonButtonEditorMacroEditScrollFrame3:GetWidth()*0.92)
		button:SetHeight(MacaroonButtonEditorMacroEditScrollFrame3:GetHeight()/7)
		button:Show()

		if (not lastButton) then
			button:SetPoint("TOPLEFT",5,-(button:GetHeight()*0.85))
			lastButton = button
		else
			button:SetPoint("TOPLEFT", lastButton, "BOTTOMLEFT", 0, -2)
			lastButton = button
		end
	end

	Macaroon.ButtonEdit_AddPanel(self, "macro")

	self:Hide()
end

function Macaroon.MacroEditIcon_OnLoad(self)

	self:SetScale(1.2)
	self.elapsed = 0
	self.click = false
end

function Macaroon.MacroEditIcon_OnClick(self, button)

	PlaySound("gsTitleOptionOK")
	local frame = getglobal(self:GetParent():GetName().."ScrollFrame2")

	if (frame:IsVisible()) then
		frame:Hide()
	else
		frame:Show()
	end

	self.click = true
end

function Macaroon.MacroEditIcon_OnEnter(self)

	self.enter = 1;
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
	GameTooltip:SetText(MACAROON_STRINGS.MACRO_ICON)
end

function Macaroon.MacroEditIcon_OnLeave(self)

	self.updateTooltip = nil
	GameTooltip:Hide()
end

function Macaroon.MacroEditIcon_OnUpdate(self, elapsed)

	self.elapsed = self.elapsed + elapsed

	if (self.elapsed > 0.1 and self.click) then
		self:SetChecked(nil)
	end
end

function Macaroon.ActionEditor_OnLoad(self)

	Macaroon.ButtonEdit_AddPanel(self, "action")
	Macaroon.ButtonEdit_AddPanel(self, "pet")

	self:Hide()
end

function Macaroon.ActionEditor_OnShow(self)

end

function Macaroon.ActionEditSlider_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button) then

		if (button.config.type == "action") then

			self:SetMinMaxValues(1, Macaroon.maxActionID)
			_G[self:GetName().."High"]:SetText(Macaroon.maxActionID)

		elseif (button.config.type == "pet") then

			self:SetMinMaxValues(1, Macaroon.maxPetID)
			_G[self:GetName().."High"]:SetText(Macaroon.maxPetID)
		end

		self:SetValue(button.config.action)
		_G[self:GetParent():GetName().."SliderEdit"]:SetText(button.config.action)

	end

end

function Macaroon.ActionEditSlider_OnValueChanged(self)

	local button = Macaroon.CurrentButton

	if (button) then

		button.config.action = self:GetValue()
		_G[self:GetParent():GetName().."SliderEdit"]:SetText(button.config.action)

		Macaroon.SetButtonType(button)
	end

end

function Macaroon.ActionEditPropagate_OnClick(self)

	local button = Macaroon.CurrentButton

	if (button) then

		for index,btn in pairs(Macaroon.Buttons) do

			if (button ~= btn[1] and button.config.type == btn[1].config.type and button.bar == btn[1].bar) then

				if (btn[1]:GetAttribute("showstates")) then

					for showstate in gmatch(btn[1]:GetAttribute("showstates"), "[^;]+") do

						if (find(button:GetAttribute("showstates"), showstate)) then

							local offset = button.config.barPos - btn[1].config.barPos

							btn[1].config.action = button.config.action - offset

							if (btn[1].config.action < 1) then
								btn[1].config.action = 1
							end

							if (btn[1].config.type == "action" and btn[1].config.action > Macaroon.maxActionID) then

								while (btn[1].config.action > Macaroon.maxActionID) do
									btn[1].config.action = btn[1].config.action - Macaroon.maxActionID
								end

							elseif (btn[1].config.type == "pet" and btn[1].config.action > Macaroon.maxPetID) then

								while (btn[1].config.action > Macaroon.maxPetID) do
									btn[1].config.action = btn[1].config.action - Macaroon.maxPetID
								end
							end

							Macaroon.SetButtonType(btn[1])
						end
					end
				end
			end
		end
	end
end

function Macaroon.ButtonOptions_OnClick(self)

	if (self.button == "close") then
		Macaroon.MacroEditor_SaveMacro()
		MacaroonButtonOptions.shrink = true
	end

end

function Macaroon.ButtonOptions_OnEvent(self, event, ...)

	--local func = function()

		--local dockFrame = Trinity2DockFrameOptions.currFrame

		--if (dockFrame) then

			--local button = Trinity2DockFrameOptionsButtonDesignButton

			--button.hasAction = dockFrame.hasAction
			--button.noAction = dockFrame.noAction

			--if (dockFrame == dedBars.docks.menu) then
			--	button.trinitytype = "menu"
			--else
			--	button.trinitytype = nil
			--end

			--TrinityBars2.SkinButton(button, dockFrame.config.skin, dockFrame.config.buttonLayout)

			--TrinityBars2.UpdateButtonOptions(dockFrame, r, g, b)
		--end
	--end

	self:Hide()

end

function Macaroon.ButtonOptions_OnUpdate(self)

	if (self.grow) then

		if (ss.checkButtons[203]) then

			if (self.scale < 1) then
				self.scale = self.scale + 0.1
				self:SetScale(self.scale)
			else
				self:SetScale(1)
				self.grow = false
			end
		else
			self:SetScale(1)
			self.grow = false
		end

	elseif (self.shrink) then

		if (ss.checkButtons[203]) then

			if (self.scale > 0.1) then
				self.scale = self.scale - 0.1
				self:SetScale(self.scale)
			else
				self:SetScale(0.01)
				self:Hide()
				self.shrink = false
			end
		else
			self:SetScale(0.01)
			self:Hide()
			self.shrink = false
		end
	end
end

function Macaroon.ButtonOptionsButton_OnLoad(self)

	local objects = getChildrenAndRegions(self)

	for k,v in pairs(objects) do
		local name = gsub(v, self:GetName(), "")
		self[lower(name)] = _G[v]
	end

	self.hotkey:SetText("K")
	self.hotkey:Hide()
	self.count:SetText("0")
	self.count:Hide()
	self.name:SetText("Name")
	self.name:Hide()
	self.cooldowntext:SetText("5")
	self.cooldowntext:Hide()
	self.cooldowntexthuge:SetText("5")
	self.cooldowntexthuge:Hide()

	self.iconframeicon:SetTexture("Interface\\Icons\\INV_Misc_Orb_05")
	self.iconframeicon:SetTexCoord(0.05, 0.95, 0.05, 0.95)

	self:SetScale(1.4)
	self:SetScale(1.3)
end

function Macaroon.ButtonOptionsEdit1_OnShow(self)

	--Trinity2.EditBox_PopUpInitialize(self.popup, TrinityBars2.ButtonDesignActions)
	self:ClearFocus()
end

function Macaroon.ButtonOptionsEdit1_OnTextChanged(self)

	--if (TrinityBars2.ButtonDesignActions[self:GetText()]) then

		--local var1, var2, var3, var4, var5, var6 = TrinityBars2.ButtonDesignActions[self:GetText()][1](Trinity2DockFrameOptions.currFrame)

		--if (var1) then
		--	Trinity2DockFrameOptionsButtonDesignEdit2:SetText(var1)
		--end

		--if (var2) then
		--	Trinity2DockFrameOptionsButtonDesignEdit3:SetText(var2)
		--end

		--Trinity2DockFrameOptionsButtonDesignPositionUp.func = TrinityBars2.ButtonDesignActions[self:GetText()][1]
		--Trinity2DockFrameOptionsButtonDesignPositionDown.func = TrinityBars2.ButtonDesignActions[self:GetText()][1]
		--Trinity2DockFrameOptionsButtonDesignPositionLeft.func = TrinityBars2.ButtonDesignActions[self:GetText()][1]
		--Trinity2DockFrameOptionsButtonDesignPositionRight.func = TrinityBars2.ButtonDesignActions[self:GetText()][1]
	--end

end

local function anchorChild_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button) then

		local data = { ["-none-"] = "none" }

		for k,v in pairs(Macaroon.BarIndexByName) do
			data[k] = v
		end

		Macaroon.EditBox_PopUpInitialize(self.popup, data)
	end
end

local function anchorChild_OnTextChanged(self)

	local button, text = Macaroon.CurrentButton, self:GetText()

	if (button and text) then

		local bar

		if (text == "-none-") then
			button.config.anchoredBar = false
			bar = Macaroon.BarIndexByName[button.config.anchoredBar]
		else
			button.config.anchoredBar = text
			bar = Macaroon.BarIndexByName[text]
		end

		if (bar) then
			Macaroon.SetAnchorChild(bar.handler, button)
		end
	end
end

local function delayEdit_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button) then

		if (button.config.anchorDelay) then
			self:SetText(button.config.anchorDelay)
		else
			self:SetText("-none-")
		end
	end
end

local function delayEdit_OnTextChanged(self)

	local button, text = Macaroon.CurrentButton, tonumber(self:GetText())

	if (button) then

		if (not text or (text and text <= 0)) then
			button.config.anchorDelay = false
		else
			button.config.anchorDelay = text
		end

		Macaroon.SetAnchor(button)
	end

end

function Macaroon.BuildAnchorOptions(self)

	local frame

	frame = CreateFrame("CheckButton", "$parentCheck301", self, "MacaroonOptionCBTemplate")
	frame:SetID(301)
	frame.text:SetText(MACAROON_STRINGS.CLICK_ANCHOR)
	frame:SetPoint("TOPLEFT", self, "TOPLEFT", 8, -8)
	self.clickanchor = frame

	frame = CreateFrame("CheckButton", "$parentCheck302", self, "MacaroonOptionCBTemplate")
	frame:SetID(302)
	frame.text:SetText(MACAROON_STRINGS.MOUSE_ANCHOR)
	frame:SetPoint("TOP", "$parentCheck301", "BOTTOM", 0, -1)
	self.mouseanchor = frame

	frame = CreateFrame("EditBox", "$parentAnchorChild", self, "MacaroonEditBoxTemplate1")
	frame:SetWidth(91)
	frame:SetHeight(20)
	frame:SetTextInsets(7,3,0,0)
	frame.text:SetText(MACAROON_STRINGS.ANCHOR_CHILD)
	frame:SetPoint("TOPRIGHT", self, "TOPRIGHT", -25, -8)
	frame:SetScript("OnTextChanged", anchorChild_OnTextChanged)
	frame:SetScript("OnShow", anchorChild_OnShow)
	frame:SetScript("OnEditFocusGained", function(self) self:ClearFocus() end)
	self.anchorchild = frame

	frame = CreateFrame("EditBox", "$parentDelayEdit", self, "MacaroonEditBoxTemplate2")
	frame:SetWidth(54)
	frame:SetHeight(20)
	frame:SetTextInsets(7,3,0,0)
	frame:SetJustifyH("CENTER")
	frame.text:SetText(MACAROON_STRINGS.ANCHOR_DELAY)
	frame:SetPoint("TOPRIGHT", self.anchorchild, "BOTTOMRIGHT", 0, -1)
	frame:SetScript("OnTextChanged", delayEdit_OnTextChanged)
	frame:SetScript("OnShow", delayEdit_OnShow)
	frame:SetScript("OnEditFocusGained", function(self) self:HighlightText() end)
	self.delay = frame

	self.clickanchor.mouseanchor = self.mouseanchor
	self.clickanchor.anchorchild = self.anchorchild
	self.clickanchor.delay = self.delay

	self.mouseanchor.clickanchor = self.clickanchor
	self.mouseanchor.anchorchild = self.anchorchild
	self.mouseanchor.delay = self.delay

end

function Macaroon.AnchorOptions_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button) then

		self.clickanchor:SetChecked(button.config.clickAnchor)
		self.mouseanchor:SetChecked(button.config.mouseAnchor)

		if (button.config.anchoredBar) then
			self.anchorchild:SetText(button.config.anchoredBar)
		else
			self.anchorchild:SetText("-none-")
		end

		self.anchorchild:SetCursorPosition(0)
		self.delay:SetCursorPosition(0)
	end

end

function Macaroon.AnchorOptions_OnHide(self)

end

function Macaroon.ButtonOptionsButton_OnClick(self, action)

	PlaySound("gsTitleOptionOK")

	local editframe = Macaroon.CurrentButton.editframe

	if (action) then

		editframe.message:SetText(MACAROON_STRINGS["BTNOPTION_EDIT_BUTTON_"..self:GetID()].."|r")

		editframe.action = action

		editframe.hover = true
	end

	MacaroonButtonOptions.shrink = true
end

function Macaroon.ButtonOptionsCheck_OnClick(self, action)

	PlaySound("gsTitleOptionOK")

	local button, checked, option = Macaroon.CurrentButton, self:GetChecked()

	for k,v in pairs(toggleOptions) do
		if (v == action) then
			option = k
		end
	end

	if (button) then

		if (checked) then
			button.config[option] = true

			if (option == "spellCounts") then
				button.config.comboCounts = false
			end

			if (option == "comboCounts") then
				button.config.spellCounts = false
			end
		else
			button.config[option] = false
		end
	end

	button.updateClicks(button)

	Macaroon.ButtonOptions_OnShow(self:GetParent())

end

function Macaroon.BuildButtonOptions(self)

	local breakIndex, xOffset, index, frame, lastFrame, anchorFrame, lastButton, iOffset = 1, 5, 1

	while (MACAROON_STRINGS["BTNOPTION_EDIT_BUTTON_"..breakIndex]) do
		breakIndex = breakIndex + 1
	end

	local yOffset = (self:GetHeight()-((breakIndex+1)*16))/breakIndex+1

	while (MACAROON_STRINGS["BTNOPTION_EDIT_BUTTON_"..index]) do

		frame = CreateFrame("Button", "$parentButton"..index, self, "MacaroonButtonTemplate2")
		frame:SetID(index)
		frame:SetWidth(110)
		frame:SetHeight(20)
		frame:SetScript("OnClick", function(self, button) Macaroon.ButtonOptionsButton_OnClick(self, self.action) end)
		frame.text = _G[frame:GetName().."Text"]
		frame.text:SetText(MACAROON_STRINGS["BTNOPTION_EDIT_BUTTON_"..index])
		frame.action = frame.text:GetText()

		if (index == 1 or index == breakIndex) then
			if (anchorFrame) then
				frame:SetPoint("TOPLEFT", anchorFrame, "TOPRIGHT", 2, 0)
				anchorFrame = frame
				breakIndex = breakIndex + (breakIndex - 1)
			else
				frame:SetPoint("TOPLEFT", self, "TOPLEFT", xOffset, -7)
				anchorFrame = frame
			end
			lastFrame = frame
		else
			frame:SetPoint("TOP", lastFrame, "BOTTOM", 0, -(yOffset))
			lastFrame = frame
		end

		lastButton = frame

		index = index + 1
	end

	breakIndex = 1; iOffset = 0

	while (MACAROON_STRINGS["BTNOPTION_EDIT_CHECK_"..breakIndex]) do

		if (MACAROON_STRINGS["BTNOPTION_EDIT_CHECK_"..breakIndex] == "exclude") then
			iOffset = iOffset + 1
		end

		breakIndex = breakIndex + 1
	end

	yOffset = (self:GetHeight()-((breakIndex-iOffset)*20))/breakIndex+1+iOffset

	xOffset, index, frame, lastFrame, anchorFrame, iOffset = -90, 1, nil, nil, nil, 0

	while (MACAROON_STRINGS["BTNOPTION_EDIT_CHECK_"..index]) do

		if (MACAROON_STRINGS["BTNOPTION_EDIT_CHECK_"..index] == "exclude") then

			iOffset = iOffset + 1

		else

			frame = CreateFrame("CheckButton", "$parentCheck"..index-iOffset, self, "MacaroonOptionCBTemplate")
			frame:SetID(index-iOffset)
			frame:SetScript("OnClick", function(self, button) Macaroon.ButtonOptionsCheck_OnClick(self, self.action) end)
			frame:SetScript("OnShow", function(self) end)
			frame.text = _G[frame:GetName().."Text"]
			frame.text:SetText(MACAROON_STRINGS["BTNOPTION_EDIT_CHECK_"..index])
			frame.action = frame.text:GetText()
			self["check"..index-iOffset] = frame

			if (index == 1 or index == breakIndex) then
				if (anchorFrame) then
					frame:SetPoint("TOPLEFT", anchorFrame, "TOPRIGHT", 2, 0)
					anchorFrame = frame
					breakIndex = breakIndex + (breakIndex - 1)
				else
					frame:SetPoint("TOPRIGHT", self, "TOPRIGHT", xOffset, -(yOffset+7-iOffset))
					anchorFrame = frame
				end
				lastFrame = frame
			else
				frame:SetPoint("TOP", lastFrame, "BOTTOM", 0, -(yOffset))
				lastFrame = frame
			end
		end

		index = index + 1
	end
end

function Macaroon.ButtonOptions_OnShow(self)

	local button = Macaroon.CurrentButton

	if (button) then

		if (not button.config.upClicks and not button.config.downClicks) then

			if (ss.registerForClicks == "AnyUp") then
				self.check1:SetChecked(1)
				self.check2:SetChecked(nil)
			else
				self.check1:SetChecked(nil)
				self.check2:SetChecked(1)
			end

		else
			self.check1:SetChecked(button.config.upClicks)
			self.check2:SetChecked(button.config.downClicks)
		end

		if (UnitClass("player") == MACAROON_STRINGS.DRUID) then

			if (button.config.spellCounts) then
				self.check3:SetChecked(1)
				self.check4:SetChecked(nil)
			else
				self.check3:SetChecked(nil)
			end

			if (button.config.comboCounts) then
				self.check4:SetChecked(1)
				self.check3:SetChecked(nil)
			else
				self.check4:SetChecked(nil)
			end

		elseif (UnitClass("player") == MACAROON_STRINGS.ROGUE) then

			if (button.config.comboCounts) then
				self.check3:SetChecked(1)
			else
				self.check3:SetChecked(nil)
			end

		else

			if (button.config.spellCounts) then
				self.check3:SetChecked(1)
			else
				self.check3:SetChecked(nil)
			end
		end
	end
end

function Macaroon.ButtonOptions_OnHide(self)

end

local function controlOnEvent(self, event, ...)

	if (event == "VARIABLES_LOADED") then

		ss = MacaroonSavedState

		hooksecurefunc("SpellButton_OnModifiedClick", modifiedSpellClick)
		hooksecurefunc("HandleModifiedItemClick", modifiedItemClick)
		hooksecurefunc("CompanionButton_OnModifiedClick", modifiedCompanionClick)
		hooksecurefunc("OpenStackSplitFrame", openStackSplitFrame)

		macroEdit = MacaroonButtonEditorMacroEditScrollFrame1Edit1
		macroFrame = MacaroonButtonEditorMacroEdit

		toggleOptions.upClicks = MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_1
		toggleOptions.downClicks = MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_2
		toggleOptions.spellCounts = MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_3
		toggleOptions.comboCounts = MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_4

		if (UnitClass("player") == MACAROON_STRINGS.ROGUE) then
			MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_3 = "exclude"
		elseif (UnitClass("player") ~= MACAROON_STRINGS.DRUID) then
			MACAROON_STRINGS.BTNOPTION_EDIT_CHECK_4 = "exclude"
		end

	elseif (event == "PLAYER_ENTERING_WORLD") then

		playerEnteredWorld = true

	elseif (event == "ACTIONBAR_SHOWGRID") then

		if (editMode) then
			for k,v in pairs(Macaroon.EditFrames) do
				if (v:IsVisible()) then
					v:GetParent().editmode = nil
					v.showgrid = true
					v:Hide()
				end
			end
		end

	elseif (event == "ACTIONBAR_HIDEGRID") then

		if (editMode) then
			for k,v in pairs(Macaroon.EditFrames) do
				if (v.showgrid) then
					v:Show()
					v.showgrid = nil
					v:GetParent().editmode = true
				end
			end
		end
	end
end

local frame = CreateFrame("Frame", nil, UIParent)
frame:SetScript("OnEvent", controlOnEvent)
frame:RegisterEvent("VARIABLES_LOADED")
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
frame:RegisterEvent("ACTIONBAR_SHOWGRID")
frame:RegisterEvent("ACTIONBAR_HIDEGRID")